// pages/car/car.js
import {
	showModal
} from "../../request/showModal.js";
Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		address: {},
		carList: [],
		allChecked: false,
		totalPrice: 0,
		total: 0
	},

	onShow() {
		const address = wx.getStorageSync("address");
		const carList = wx.getStorageSync("cart_detail") || [];
		const allChecked = carList.length ? carList.every(v => v.Choose) : false
		this.setData({
			address
		});
		this.setCarChange(carList);
	},
	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: function(options) {

	},
	async users_Address() {
		const result = await wx.chooseAddress({})
			.then(res => {
				res.allAddress = res.provinceName + res.cityName + res.countyName + res.detailInfo;
				wx.setStorageSync("address", res)
			}).catch(err => {
				console.log(err);
			})

	},

	//商品选中状态
	handleItemChange(e) {
		const id = e.currentTarget.dataset.id;
		let {
			carList
		} = this.data;
		let index = carList.findIndex(v => v.goods_id === id);
		carList[index].Choose = !carList[index].Choose;
		this.setCarChange(carList);

	},

	//全选
	handleAllCheck() {
		let {
			carList,
			allChecked
		} = this.data;
		allChecked = !allChecked;
		carList.forEach(v => {
			v.Choose = allChecked
		});
		this.setCarChange(carList);
	},


	async handleNumChange(e) {
		const {
			num,
			id
		} = e.currentTarget.dataset;
		console.log(e);
		let {
			carList
		} = this.data;
		let index = carList.findIndex(v => v.goods_id === id);
		if (carList[index].num === 0 && num === -1) {
			const res = await showModal({
				content: "您是否要删除此商品？"
			});
			if (res.confirm) {
				carList.splice(index, 1);
				this.setCarChange(carList);
			}
		} else {
			carList[index].num += num;
		}
		this.setCarChange(carList);

	},
	
	//结算
	PayOfBuy(){
		const {address,total} = this.data;
		const userInfo = wx.getStorageSync("userInfo");
		if(!address.userName){
			wx.showToast({
				title:"您还没有添加收货地址",
				icon:"none",
				mask:true
			})
			return;
		};
		if(!userInfo){
			wx.showToast({
				title:"请先前往 我的 登录",
				icon:"none",
				mask:true
			})
			return;
		}
		if(total === 0 ){
			wx.showToast({
				title:"您什么都没打算买呢",
				icon:"none",
				mask:true
			})
			return;
		};
		wx.navigateTo({
			url:"/pages/Pay/Pay"
		})
	},



	//封装
	setCarChange(carList) {
		let totalPrice = 0;
		let total = 0;
		let allChecked = true;
		carList.forEach((v, i) => {
			if (v.Choose) {
				totalPrice += v.goods_price * v.num;
				total += v.num
			} else {
				allChecked = false;
			}
		})
		this.setData({
			carList,
			totalPrice,
			total,
			allChecked
		});
		wx.setStorageSync("cart_detail", carList)
	}
})
